package com.activity.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.example.login.R;

import java.util.Objects;

public class ShopFragment extends Fragment {
    private RadioButton goodsRb, secRb;
    private GoodsFragment goodsFragment;
    private SecGoodsFragment secGoodsFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shop,container,false);
        goodsRb = view.findViewById(R.id.shop_goods_RB);
        secRb = view.findViewById(R.id.shop_sec_RB);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        initGoods();

        goodsRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    initGoods();
                }
            }
        });

        secRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    initSecGoods();
                }
            }
        });
    }

    private void initGoods(){
        FragmentTransaction transaction = Objects.requireNonNull(getActivity()).getSupportFragmentManager().beginTransaction();

        if(goodsFragment == null){
            goodsFragment = new GoodsFragment();
            transaction.add(R.id.shop_fragment, goodsFragment);
        }
        hideFragment(transaction);
        transaction.show(goodsFragment);
        transaction.commit();
    }

    private void initSecGoods(){
        FragmentTransaction transaction = Objects.requireNonNull(getActivity()).getSupportFragmentManager().beginTransaction();

        if(secGoodsFragment == null){
            secGoodsFragment = new SecGoodsFragment();
            transaction.add(R.id.shop_fragment, secGoodsFragment);
        }
        hideFragment(transaction);
        transaction.show(secGoodsFragment);
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction){
        if(goodsFragment != null){
            transaction.hide(goodsFragment);
        }
        if(secGoodsFragment != null){
            transaction.hide(secGoodsFragment);
        }
    }
}
